package com.example.register.config;

import com.example.register.EventType;
import com.example.register.service.ServerService;
import com.example.registerapi.RegisterInfo;
import com.example.registerapi.RegisterInfoHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Set;

@Component
public class ServiceCheckConfig {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ServerService serverService;

    @Scheduled(fixedRate = 5000)
    public void serviceCheck() {
        List<RegisterInfo> allRegisterInfos = RegisterInfoHolder.getAllRegisterInfos();
        for (RegisterInfo server : allRegisterInfos) {
            String url = String.format("%s", server.getHost()+ "/health");
            try {
                restTemplate.getForObject(url, String.class);
                if (!server.isOnline()){
                    serverService.publishEvent(server, EventType.REGISTER);
                }
            }catch (Exception e){
                // 设置状态
                server.setOnline(false);
                // 发布通知
                serverService.publishEvent(server, EventType.OFFLINE);
                System.out.println("服务检测失败："+e.getMessage());
            }

        }
    }
}
